class SourcesController < ApplicationController
  before_filter :login_required, :only=>[:new, :edit, :destroy]

  # GET /sources
  # GET /sources.xml
  def index
    @sources = Source.paginate :all,  :page => params[:page], :per_page=>Bookmark::PER_PAGE, :order => 'created_at DESC'

    @mytags=get_all_tags(50)

    respond_to do |format|
      format.html # index.html.erb
      format.xml  { render :xml => @sources }
    end
  end

  def tags
    @alltags = get_all_tags(200)
  end

  # GET /sources/1
  # GET /sources/1.xml
  def show
    @source = Source.find(params[:id])

    respond_to do |format|
      format.html # show.html.erb
      format.xml  { render :xml => @source }
    end
  end

  # GET /sources/new
  # GET /sources/new.xml
  def new
    @source = Source.new

    respond_to do |format|
      format.html # new.html.erb
      format.xml  { render :xml => @source }
    end
  end

  # GET /sources/1/edit
  def edit
    @source = Source.find(params[:id])
  end

  # POST /sources
  # POST /sources.xml
  def create
    @source = Source.find_by_uri(params[:source][:uri])
    if @source.nil?
      @source = Source.new(params[:source])
    end
    if @source.first_poster.blank?
      @source.first_poster = current_user.login if logged_in?
    end
    if @source.save
      flash[:source_id] = @source.id
      redirect_to(new_bookmark_path)
    else
      render :action => "new"
    end

#    respond_to do |format|
#      if @source.save
#        #flash[:notice] = 'Source was successfully created.'
#        format.html { redirect_to(new_bookmark_path) }
#
#      else
#        format.html { render :action => "new" }
#        format.xml  { render :xml => @source.errors, :status => :unprocessable_entity }
#      end
#    end
  end

  # PUT /sources/1
  # PUT /sources/1.xml
  def update
    @source = Source.find(params[:id])

    respond_to do |format|
      if @source.update_attributes(params[:source])
        flash[:notice] = 'Source was successfully updated.'
        format.html { redirect_to(@source) }
        format.xml  { head :ok }
      else
        format.html { render :action => "edit" }
        format.xml  { render :xml => @source.errors, :status => :unprocessable_entity }
      end
    end
  end

  # DELETE /sources/1
  # DELETE /sources/1.xml
  def destroy
    @source = Source.find(params[:id])
    @source.destroy

    respond_to do |format|
      format.html { redirect_to(sources_url) }
      format.xml  { head :ok }
    end
  end

end
